/**
 * SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
 * SPDX-License-Identifier: Mulan PSL v2
 */
<!--
 * @Author: zhb
 * @Date: 2020-08-28
 * @Description: es数据源表单配置
 -->
<template>
    <div class="load-data-set__form operate_form">
        <sf-form ref="esDataSetForm"
                 :label-width="100">
            <sf-form-item class="datasource-from">
                <sf-fieldlabel>
                    <lang>数据来源</lang>
                </sf-fieldlabel>
                <div class="datasource-list">
                    <div 
                        v-for="(item,index) in datasourceList"
                        :key="index"
                        class="datasource-type__item"
                        :class="activeIndex === index ? 'active':''"
                        @click="selectDataType(index)">
                        {{ item.name }}
                    </div>
                </div>
            </sf-form-item>
            <div v-if="activeIndex===0">
                <sf-form-item>
                    <sf-fieldlabel>
                        <lang>选择数据源</lang>
                    </sf-fieldlabel>
                    <sf-textfield
                        ref="uploadTextField"
                        v-model="formData.csvFilepath"
                        :default-width="372"
                        :placeholder="_('请选择一个csv文件')"
                        :allow-blank="false"
                        :default-disabled="true" />
                    <sf-button-primary 
                        ref="button-primary"
                        class="sfv-btn-primary"
                        @click="_selectSaveFile">
                        <lang>选择</lang>
                    </sf-button-primary>
                </sf-form-item>
                <sf-form-item>
                    <sf-fieldlabel>
                        <lang>选择文件格式</lang>
                    </sf-fieldlabel>
                    <sf-select
                        v-model="formData.csvFileEncoding"
                        :default-width="fieldWidth"
                        :allow-search="true"
                        :allow-blank="false"
                        :options="csvFileEncodingList" />
                </sf-form-item>
            </div>
           
            <sf-form-item v-else>
                <sf-fieldlabel>
                    <lang>选择数据源</lang>
                </sf-fieldlabel>
                <sf-select
                    v-model="formData.dataSourceId"
                    :default-width="fieldWidth"
                    :allow-search="true"
                    :allow-blank="false"
                    :options="sourceList" />
            </sf-form-item>
            <sf-form-item v-if="showIndexSelect && activeIndex!==0">
                <sf-fieldlabel>
                    {{ sourceTitle }}
                </sf-fieldlabel>
                <sf-select
                    v-model="formData.index"
                    :default-width="fieldIndexWidth"
                    :allow-search="true"
                    :allow-blank="false"
                    :options="tableNameList" />
                <i
                    id="sf-id-192"
                    v-qtip="sourceTips"
                    qanchor="bottom-end"
                    class="sfv-fieldtip sfv-fieldtip_icon sf-comp-iconfont icon-comp-info"
                    sfv="">
                </i>
            </sf-form-item>
        </sf-form>
        <div v-if="!isEdit"
             class="submit-datasource">
            <sf-button-primary class="submit-btn"
                               @click="_submitSource">
                <lang>确定</lang>
            </sf-button-primary>
            <sf-button @click="_quit">
                <lang>清空</lang>
            </sf-button>
        </div>
    </div>
</template>

<script>
import {
    ES_DATA_SET_DEFAULT_DATA
} from 'src/home/mod_cluster/project_manager/feature_manager/const_data';

import urlAdapter from 'src/home/mod_common/url_adapter';
const ADD_DEFAULT_WIDTH = 456;
const ADD_DEFAULT_INDEX_WIDTH = 434;
import { deepClone } from 'src/util/deep_clone';

// const EDIT_DEFAULT_WIDTH = 292;
// const EDIT_DEFAULT_INDEX_WIDTH = 270;

import selectFileTable from './select_file_table.vue';

import store from 'src/vuex/store';
let userID = store.state.userId;

const DATA_SORECE_TYPE = {
    'es' :'es',
    'mongdb':'mongdb',
    'nebula':'nebula'
};

export default {
    name: 'LoadDataSet',
    props: {
        sourceList: {
            default: () => [],
            type: Array
        },
        isEdit:{
            default:false,
            type:Boolean
        }
    },
    data () {
        return {
            formData: { ...ES_DATA_SET_DEFAULT_DATA },
            tableNameList: [],
            sourceType: '',
            activeIndex:0,
            datasourceList:[{
                name:_('对象存储')
            }, {
                name:_('数据库')
            }],
            csvFileEncodingList:[{
                label:_('UTF-8'),
                value:_('UTF-8')
            }, {
                label:_('GBK'),
                value:_('GBK')
            }]
        };
    },
    computed: {
        fieldWidth () {
            return ADD_DEFAULT_WIDTH;
        },
        fieldIndexWidth () {
            return ADD_DEFAULT_INDEX_WIDTH;
        },
        sourceId () {
            return this.formData.dataSourceId;
        },
        sourceTitle () {
            if (this.sourceType === 'es') {
                return _('索引');
            } else if (this.sourceType === 'mongdb') {
                return _('集合');
            }
            return '';

        },
        sourceTips () {
            if (this.sourceType === 'es') {
                return _('索引对应数据库中表的概念。');
            } else if (this.sourceType === 'mongdb') {
                return _('集合对应数据库中表的概念。');
            }
            return '';
        },
        showIndexSelect () {
            return this.sourceType && this.sourceType === 'es' || this.sourceType === 'mongdb';
        }
    },
    watch: {
        sourceId: {
            deep: true,
            handler () {
                if (this.sourceList.length > 0) {
                    let list = this.sourceList.filter(item => item.value === this.sourceId);
                    this.sourceType = list.length > 0 ? DATA_SORECE_TYPE[list[0].type] : '';
                    if (this.showIndexSelect) {
                        this._getTableNameList();
                    }
                }
            }
        }
    },
    methods: {
        
        // 选择服务弹窗
        _createSelectSaveFileWin () {
            if (!this.selectSaveFileWin) {
                this.selectSaveFileWin = this.$modal(selectFileTable, {
                    autoDestory: true
                });
            }
            return this.selectSaveFileWin;
        },
         _selectSaveFile () {
            let formWin = this._createSelectSaveFileWin();
            formWin.formRoot._getWebprc(true);
            formWin.open({
                title: _('选择对象存储文件'),
                submit: () => {
                    let model = formWin.formRoot.getJsonValue() || [];
                    let tableData = formWin.formRoot.getTableData();

                    //相当于空表格，直接关闭弹窗
                    if (!tableData) {
                        formWin.hide();
                        return;
                    }
                    if (!model.length) {
                        this.$warn(_('请选择一个对象存储文件'), { autoHide: true });
                        return;
                    };
                    this.formData.csvFilepath = `s3a://${userID}/${model[0].name}`;
                    formWin.hide();
                }
            });
        },
        getOtherJsonValue () {
            let params = {};
            if (this.activeIndex === 0) {
                params = {
                    dataSourceType:'csv',
                    dataSourceName: this.formData.csvFilepath
                };
            } else {
                let dataSourceName = this.sourceList.filter(item => item.value === this.sourceId)[0].label;
                params = {
                    dataSourceName,
                    dataSourceType: this.sourceType
                };
            }
            return params;
        },
        getJsonValue () {
            let jsons = deepClone(this.formData);
            this.formData = { ...ES_DATA_SET_DEFAULT_DATA };
            if (this.activeIndex === 0) {
                this.formData.sourceType = 'csv';
                this.formData.csvFilepath = jsons.csvFilepath;
                this.formData.csvFileEncoding = jsons.csvFileEncoding;
            } else {
                this.formData.dataSourceId = jsons.dataSourceId;
                let selectList = this.sourceList.filter(item=> item.value === this.sourceId)[0];
                if (selectList) {
                    this.formData.url = selectList.url;
                    this.formData.sourceType = DATA_SORECE_TYPE[selectList.type];
                };
                if (this.formData.sourceType === 'es') {
                    this.formData.index = jsons.index;
                }

            }
            return this.formData;
        },
        setJsonValue (data) {
            Object.assign(this.formData, data);
        },

        async _getTableNameList () {
            let esqueryURL = `${urlAdapter('dataSource')}/${this.sourceId}/table`;
            this.$mask();
            let jsonData = await this.$ajax.get(esqueryURL);
            this.$unmask();
            let { success, msg, data } = jsonData;
            if (!success) {
                this.$showErr(msg || _('加载数据失败'));
                return;
            }
            this.tableNameList = [];
            data.forEach(item => {
                this.tableNameList.push({
                    label: item,
                    value: item
                });
            });
        },
        selectDataType (index) {
            this.activeIndex = index;
        },
        _submitSource () {
            this.$emit('submit-datasource');
        },
        _reset () {
            this.sourceType = '';
            this.formData = { ...ES_DATA_SET_DEFAULT_DATA };
            this.$nextTick(()=>{
                this.$refs.esDataSetForm.clearInvalid();
            });
        },
        _quit () {
            this._reset();
        }
    }
};
</script>

<style lang="less">
.load-data-set__form {
    text-align: center;
    height: calc(100% - 162px);
    position: relative;
    .datasource-from{
        display: flex;
        justify-content: center;
        margin-bottom: 40px;
        margin-top: 10px;
        align-items: center;
    }
    .datasource-list{
        display: flex;
        margin-left: 3px;
        .datasource-type__item{
            flex: 1;
            width: 228px;
            height: 38px;
            line-height: 38px;
            text-align: center;
            border:1px solid #ddd;
            cursor: pointer;
            &.active{
                background: #204ED9;
                color: #fff;
            }
        }
    }
}
.submit-datasource {
    width: 100%;
    padding: 16px;
    .submit-btn {
        margin-left: -360px;
        margin-right: 8px;
    }
}
</style>

